#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use FindBin qw( $RealBin );
use Util;
use Logs;
use POSIX ":sys_wait_h";
use File::Basename;
use Digest::MD5;

$| ++;

=head1 SYNOPSIS

=cut

sub checkfile
{
    my ( $path, $file ) = @_;
    print "checkfile: $file\n";

    my ( $name, $version, $md5, $email );
    if( $file =~ /^([a-zA-Z0-9\._]+)@(release[a-zA-Z0-9\.\-_]+)$/ )
    {
        ( $name, $version ) = ( $1, $2 );
    }
    elsif( $file =~ /^([a-zA-Z0-9\._]+)@(release[a-zA-Z0-9\.\-_]+)@([a-z0-9]{32})$/ )
    {
        ( $name, $version, $md5 ) = ( $1, $2, $3 );
    }
    elsif( $file =~ /^([a-zA-Z0-9\._]+)@(release[a-zA-Z0-9\.\-_]+)@([a-z0-9]{32})@([a-z0-9\.]+@[a-z0-9\.]+)$/ )
    {
        ( $name, $version, $md5, $email ) = ( $1, $2, $3, $4 );
        system "echo '$email' > $path/mail/$name\@$version";
    }
    else
    {
        unlink "$path/curr/$file";
        die "unlink $path/curr/$file : filename format error\n";
    }

    if( defined $md5 )
    {
        die "$file: open: $!\n" unless open my $fh => "/$path/curr/$file";
        my $m = Digest::MD5->new()->addfile( $fh )->hexdigest();
        close $fh;
        if( $md5 ne $m )
        {
            unlink "$path/curr/$file";
            die "$path/curr/$file : md5 error\n";
        }
    }
    die "move file to repo error" if system "mv '$path/curr/$file' '$path/repo/$name\@$version'";
}

return sub
{
    my %param = @_;

    my ( $interval, $logs, $path, @error ) = ( 3, Logs->new( 'pkgrsync' ), "$RealBin/../pkgrsync" );

    while( 1 )
    {
        sleep $interval;
        warn "do ...\n";
        for my $file ( map{ basename $_ } glob "$path/curr/*" )
        {
            eval{ checkfile( $path, $file ); };
            push @error, $@ if $@;
        }
        $logs->err( join ',', @error ) if @error; 
    }
}
